<template>
  <div id="testlistpanel">
    <vxe-toolbar class-name="bg-orange light">
      <template #buttons>
        <span class="padding-lr-xs">
          <vxe-button
            type="text"
            content="刷新"
            class-name="padding-lr-xs"
            class="button-blue padding-lr-xs"
            @click="getImage()"
          />
        </span>
        <span class="padding-lr-xs">
          <el-upload
            class="upload-demo"
            :data="paramData"
            :headers="headers"
            :action="uploadFilePath"
            :show-file-list="false"
            multiple
            :on-success="onSuccess"
            :on-error="onError"
            :disabled="uploadDisabled"
          >
            <vxe-button
              type="text"
              :disabled="uploadDisabled"
              content="上传"
              class-name="padding-lr-xs"
              class="button-blue padding-lr-xs"
              @click="upload()"
            />
          </el-upload>
        </span>
        <span class="padding-lr-xs">
          <el-upload
            class="upload-demo"
            :data="paramData"
            :headers="headers"
            :action="uploadFilePath"
            :show-file-list="false"
            multiple
            :on-success="onSuccess"
            :on-error="onError"
            :disabled="disabled"
          >
            <vxe-button
              type="text"
              :disabled="disabled"
              content="重新上传"
              class-name="padding-lr-xs"
              class="button-blue padding-lr-xs"
              @click="reupload(currentFileList)"
            />
          </el-upload>
        </span>
        <span class="padding-lr-xs">
          <vxe-button
            type="text"
            :disabled="deleteDisabled"
            content="批量删除"
            class-name="padding-lr-xs"
            class="button-red padding-lr-xs"
            @click="batchDeleteImages(currentFileList)"
          />
        </span>
      </template>
    </vxe-toolbar>
    <div style="height: calc(100% - 30px - 40px - 2px - 38px)">
      <div
        class="main-img"
        ref="mainImg"
        v-loading="loading"
        :style="{ height:'calc(100% - 40px)' }"
      >
        <el-scrollbar height="100%">
          <ul class="img-box">
            <li
              v-for="(item, index) in wLFileList"
              :key="index"
              :style="{
              width: imgWidth + 'px',
              height: imgHeight + 'px',
            }"
            >
              <el-image :src="picUrlBase + item.imageUrl" :preview-src-list="wLFullPathFileList" :initial-index="index"></el-image>
              <el-checkbox v-model="item.isChecked" @change="val => selectFile(val, item)"></el-checkbox>
              <el-link :underline="false">
                <i v-if="deleteDisabled === false" class="vxe-icon-error-circle-fill" @click="handleDelete(item.id)"></i>
              </el-link>
            </li>
          </ul>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { UploadProps } from 'element-plus';
import VXETable from 'vxe-table';
import 'vxe-table/lib/style.css';
import { IsEmpty } from '../../../../utils/common';

let images: any = reactive([]); //图片信息集合
let isChk = ref(0); //是否审核
let disabled = ref(true);
let uploadDisabled = ref(true);
let deleteDisabled = ref(true);
let picUrlBase = (window as any).apiUrl.VITE_SERVER_URL;
let wLFileList = reactive([]);
let wLFullPathFileList = reactive([]);
let currentFileList = reactive([]); //当前选中的文件数组
let id = ''; //接收传过来的检验结果id
let imgWidth = null;
let imgHeight = null; //图片高度，图片宽高比需要为4:3
let loading = false;
let headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
};

// 请求参数数据
const paramData = reactive({
  rptGroup:'',
  sampleda:'',
  sampleNo:'',
  id: id //检验图片id
});

defineExpose({
  getImageData
});

// 页面加载列表
function getImageData(repData: any) {
  if (IsEmpty(repData) || IsEmpty(repData.id)) {
    paramData.rptGroup = '';
    paramData.sampleda = '';
    paramData.sampleNo = '';
    //清除旧数据
    disabled.value = true;
    currentFileList.length = 0;
    wLFullPathFileList.length = 0;
    wLFileList.length = 0;
    return;
  }
  isChk.value=repData.isChk;
  if (repData.isChk === 0 || IsEmpty(repData.isChk)){
    uploadDisabled.value=false;
    deleteDisabled.value=false;
  }else {
    uploadDisabled.value=true;
    deleteDisabled.value=true;
  }
  paramData.rptGroup = repData.rptGroup;
  paramData.sampleda = repData.sampleda;
  paramData.sampleNo = repData.sampleNo;
  getImage();
}
// 上传图片 弹框
function upload() {
  paramData.id = '';
}
// 上传成功
function onSuccess(e) {
  if (e && e.status && e.status.code && e.status.code === 400) {
    VxeMessage(e.status.msg.replace('IOException: ', ''), VxeNotifyType.error);
    return;
  }
  getImage();
}
//上传失败
function onError(e) {
  console.log('失败', e);
}
//重新上传
async function reupload(arr) {
  if (!(arr && arr.length === 1 && arr[0])) {
    VxeMessage('请勾选一条重新上传的数据', VxeNotifyType.info);
    return;
  }
  disabled.value = false;
  paramData.id = arr[0].id;
}
//批量删除
async function batchDeleteImages(arr) {
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
    return;
  } else {
    const url = '/lab/rptresultImage/batchDeleteImages';
    const ids = [];
    for (var i = 0; i < arr.length; i++) {
      ids.push(arr[i].id);
    }
    const data = {
      eptresultImageIds: ids
    };
    proxy.$http.post(url, data).then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('批量删除成功', VxeNotifyType.success);
        getImage();
      } else {
        VxeMessage('批量删除失败', VxeNotifyType.error);
      }
    });
  }
} //批量删除
async function handleDelete(id) {
  const url = '/lab/rptresultImage/batchDeleteImages';
  const ids = [];
  ids.push(id);

  const data = {
    eptresultImageIds: ids
  };
  proxy.$http.post(url, data).then((res: any) => {
    if (res.status.code === 1) {
      VxeMessage('删除成功', VxeNotifyType.success);
      getImage();
    } else {
      VxeMessage('删除失败', VxeNotifyType.error);
    }
  });
}

// 移除文件
function fileRemove(file: any, fileList: any) {
  fileList = [];
}

// 获取图片
function getImage() {
  disabled.value = true;
  currentFileList.length = 0;
  wLFullPathFileList.length = 0;
  wLFileList.length = 0;
  const url = '/lab/rptresultImage/findImagesByMaininfoId';
  const data = {};
  proxy.$http
    .get(url, { params: {rptGroup:paramData.rptGroup,sampleda:paramData.sampleda,sampleNo:paramData.sampleNo} })
    .then(async (res: any) => {
      wLFullPathFileList.length=0;
      if (!IsEmpty(res.data) && res.data) {
        res.data.forEach((item) => {
          item.isChecked = false;
        });
        wLFileList.push(...res.data);
        wLFileList.forEach((item) => {
          wLFullPathFileList.push((window as any).apiUrl.VITE_SERVER_URL + item.imageUrl);
        });
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 选中文件
function selectFile(checked, val) {
  const index = currentFileList.findIndex((item) => {
    return item.id === val.id;
  });

  // 未勾选 且 元素在 currentFileList 中存在，删除
  if (!checked && index > -1) {
    currentFileList.splice(index, 1);
  }
  // 勾选 且 元素在 currentFileList 中没有，添加进去
  if (checked && index === -1) {
    currentFileList.push(val);
  }
  if ((isChk.value === 0 || IsEmpty(isChk.value)) && currentFileList.length>0){
    disabled.value = false;
    return;
  }else {
    disabled.value = true;

  }
}

// 超出数量提示
const handleExceed: UploadProps['onExceed'] = (files: any, uploadFiles: any) => {
  VxeMessage('只能上传一个图片', VxeNotifyType.warning);
};

// 上传图片
const uploadFilePath = ref((window as any).apiUrl.VITE_SERVER_URL + '/lab/rptresultImage/uploadImage');
</script>
<style lang="scss" scoped>
#testlistpanel {
  height: 100%;
  // 附加按钮间距
  .button-red {
    margin: 5px 0 5px 5px;
  }
  // 中间table表格
  .tableBody {
    height: 50%;
  }
  img:hover {
    transform: scale(1.2);
  }
  :deep(.vxe-body--row) {
    height: 80px;
  }
  .main-img {
    ul.img-box {
      margin: 0;
      padding: 0;
      list-style-type: none;
      overflow: hidden;

      > li {
        position: relative;
        display: inline; //让li横向排列
        padding: 5px;
        float: left;
        /*     text-decoration: none;
        list-style: none;//去掉li前面的圆点
        display: inline;//让li横向排列
        border: 1px solid #FFFFFF;
        background-color: #30DDEB;*/
      }

      .el-image {
        width: 200px;
        height: 200px;
        border: 1px #aaa solid;
        box-sizing: border-box;
      }
      .el-checkbox {
        position: absolute;
        top: 5px;
        left: 6px;
      }
      .el-link {
        position: absolute;
        top: 0px;
        right: 0px;
        i {
          margin-right: -2px;
          font-size: 16px;
        }
      }
    }
  }
}
</style>